
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "../iface/debug.h"
#include "../utils/BaseConvert.h"
#include "../utils/StringUtils.h"
#include "DSAPublicKey.h"
#include "DSAPrivateKey.h"

/** Constructor for a blank DSA private key. */
DSAPrivateKey::DSAPrivateKey()
{
   key = NULL;
   keyname = NULL;
}

/** Constructor for a blank DSA private key with a name.
 * 
 * @param name The name to attach to the blank key. */
DSAPrivateKey::DSAPrivateKey(const char *name)
{
   key = NULL;
   keyname = NULL;
   setKeyName(name);
}

/** Copy constructor for an DSA private key.
 * 
 * @param other The DSA private key to copy from. */
DSAPrivateKey::DSAPrivateKey(const DSAPrivateKey &other)
{
   key = DSA_new();
   if (key == NULL)
   {
      errprint("DSA_new failed");
      return;
   }
   copyDSASSLPrivateKey(key, other.key);
   keyname = NULL;
   setKeyName(other.keyname);
}

/** Construct the DSA private key from a PEM encoded PKCS #8 text
 * format DSA private key.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an DSA
 * private key, from which this key is to be constructed.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
DSAPrivateKey::DSAPrivateKey(const char *pemtext, const char *name)
{
   importKeyFromASCII(pemtext, name);
}

/** Construct the DSA private key from an encrypted and passworded PEM
 * encoded PKCS #8 text format DSA private key.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an DSA
 * public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the DSA public key.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
DSAPrivateKey::DSAPrivateKey(const char *pemtext, const char *password, const char *name)
{
   importKeyFromASCIIWithPassword(pemtext, password, name);
}

/** Construct the DSA private key from an DSA private key in SSL
 * format.
 * 
 * @param prvkey The SSL format DSA private key to construct this key
 * from.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
DSAPrivateKey::DSAPrivateKey(DSA *prvkey, const char *name)
{
   key = DSA_new();
   if (key == NULL)
   {
      errprint("DSA_new failed");
      return;
   }
   copyDSASSLPrivateKey(key, prvkey);
   keyname = NULL;
   setKeyName(name);
}

/** Copy assignment operator for an DSA private key.
 * 
 * @param other The DSA private key to copy from. */
DSAPrivateKey &DSAPrivateKey::operator=(const DSAPrivateKey &other)
{
   key = DSA_new();
   if (key == NULL)
   {
      errprint("DSA_new failed");
      return *this;
   }
   copyDSASSLPrivateKey(key, other.key);
   keyname = NULL;
   setKeyName(other.keyname);
   return *this;
}

/** Destructor for the DSA private key. */
DSAPrivateKey::~DSAPrivateKey()
{
   if (key) DSA_free(key);
   key = NULL;
   if (keyname) free((void *)keyname);
   keyname = NULL;
}

/** Get a copy of the private key as an SSL format object.
 * 
 * @param[out] prvkey A pointer to a place to put a pointer to the new
 * SSL format DSA private key which is a copy of this key. The
 * responsibility for freeing the new DSA in SSL format is transferred
 * to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::getSSLKeyComponents(DSA **prvkey) const
{
   *prvkey = DSA_new();
   if ((*prvkey) == NULL)
   {
      errprint("DSA_new failed");
      return -1;
   }
   return copyDSASSLPrivateKey(*prvkey, key);
}

/** Get a copy of the private key in PEM encoded PKCS #8 text format.
 * 
 * @param[out] pemtext A pointer to a place to put a pointer to the
 * exported key in PEM encoded PKCS #8 text format. The responsibility
 * for freeing the new string is transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::getPEMKeyData(char **pemtext) const
{
   return getPEMKeyData(pemtext, NULL);
}

/** Get a copy of the private key in PEM encoded and encrypted PKCS #8
 * text format, protected with the given password.
 * 
 * @param[out] pemtext A pointer to a place to put a pointer to the
 * exported key in encrypted PEM encoded PKCS #8 text format. The
 * responsibility for freeing the new string is transferred to the
 * caller.
 * 
 * @param password The password to encrypt and decrypt the key with.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::getPEMKeyData(char **pemtext, const char *password) const
{
   char *data;
   int damt;
   int retval = 0;
   BIO *bo = BIO_new(BIO_s_mem());
   if (!PEM_ASN1_write_bio((i2d_of_void *)i2d_DSAPrivateKey, PEM_STRING_DSA, bo, (char *)key, (password) ? EVP_des_ede3_cbc() : NULL, NULL, 0, 0, (void *)password))
   {
      retval = 1;
      errprint("could not export private key (password optional)");
      SSLCheckError();
      goto bioshutdown;
   }
   SSLCheckError();
   damt = BIO_get_mem_data(bo, &data);
   (*pemtext) = (char *)malloc(sizeof(char)*(damt+1));
   memcpy((*pemtext), data, sizeof(char)*(damt+1));
   (*pemtext)[damt] = '\0';
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   return retval;
}

/** Compare this PrivateKey to a PublicKey, and see if they are part
 * of the same key pair (one decrypts any content encrypted by the
 * other).
 * 
 * @param pubkey The public key to compare to this private key to see
 * if they make a valid pair.
 * 
 * @return 1 if they make a matching pair of keys, 0 if they do not,
 * and negative values represent errors. */
int DSAPrivateKey::compareKeyBelongs(PublicKey *pubkey) const
{
   if (pubkey == NULL)
   {
      errprint("comparing against NULL key");
      return 0;
   }
   switch (pubkey->getKeyType())
   {
      case KEY_TYPE_PUBLIC_DSA:
      {
         DSA *dsaKeyOther = NULL;
         ((DSAPublicKey *)pubkey)->getSSLKeyComponents(&dsaKeyOther);
         EVP_PKEY *evp1 = EVP_PKEY_new();
         EVP_PKEY *evp2 = EVP_PKEY_new();
         EVP_PKEY_set1_DSA(evp1, key);
         EVP_PKEY_set1_DSA(evp2, dsaKeyOther);
         int retval = EVP_PKEY_cmp(evp1, evp2);
         EVP_PKEY_free(evp1);
         EVP_PKEY_free(evp2);
         DSA_free(dsaKeyOther);
         SSLCheckError();
         switch (retval)
         {
            case -2:
               errprint("key compare operation not supported (EVP_PKEY_cmp())");
               break;
            case -1:
               errprint("tried to compare different key types (EVP_PKEY_cmp())");
               return 0;
            case 0:
               return 0;
            case 1:
               return 1;
         }
         return 0;
         break;
      }
      default:
      {
         return 0;
         break;
      }
   }
}

/** Copy an SSL format private key.
 * 
 * @param[out] dst Pointer to an initialised blank SSL format DSA key
 * to copy into.
 * 
 * @param src Pointer to an existing SSL format DSA private key to
 * copy from.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::copyDSASSLPrivateKey(DSA *dst, DSA *src)
{
   if (dst == NULL) { errprint("NULL private key destination"); return -1; }
   if (src == NULL) { errprint("NULL private key source"); return 1; }
   // Copy public key
   dst->p = BN_new();
   if ((src->p == NULL) || (BN_copy(dst->p, src->p) != (dst->p)))
   {
      errprint("Could not copy%s prv->p", (src->p) ? "" : " NULL");
      return -1;
   }
   dst->q = BN_new();
   if ((src->q == NULL) || (BN_copy(dst->q, src->q) != (dst->q)))
   {
      errprint("Could not copy%s prv->q", (src->q) ? "" : " NULL");
      return -1;
   }
   dst->g = BN_new();
   if ((src->g == NULL) || (BN_copy(dst->g, src->g) != (dst->g)))
   {
      errprint("Could not copy%s prv->g", (src->g) ? "" : " NULL");
      return -1;
   }

   // Copy private key
   dst->priv_key = BN_new();
   if ((src->priv_key == NULL) || (BN_copy(dst->priv_key, src->priv_key) != (dst->priv_key)))
   {
      errprint("Could not copy%s prv->priv_key (x)", (src->priv_key) ? "" : " NULL");
      return -1;
   }
   dst->pub_key = BN_new();
   if ((src->pub_key == NULL) || (BN_copy(dst->pub_key, src->pub_key) != (dst->pub_key)))
   {
      errprint("Could not copy prv->pub_key (y)", (src->pub_key) ? "" : " NULL");
      return -1;
   }
   return 0;
}

/** Import and name an DSA private key from an DSA private key in
 * encrypted PEM format PKCS #8.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an DSA
 * public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the DSA private key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::importPrivateKeyWithOptionalPassword(const char *pemtext, const char *password)
{
   if (!key) key = DSA_new();
   int retval = 0;
   BIO *bo = BIO_new_mem_buf((void *)pemtext, -1);
   if (!PEM_ASN1_read_bio((d2i_of_void *)d2i_DSAPrivateKey, PEM_STRING_DSA, bo, (void **)(&key), 0, (void *)password))
   {
      retval = 1;
      errprint("could not import private key (password optional)");
      SSLCheckError();
      goto bioshutdown;
   }
   SSLCheckError();
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   return retval;
}

/** Import an DSA private key from some PEM format PKCS #8 text.
 * 
 * @param text The PEM encoded PKCS #8 text that represents an DSA
 * public key, from which this key is to be constructed.
 * 
 * @param name The name to be attached to the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::importKeyFromASCII(const char *text, const char *name)
{
   return importKeyFromASCIIWithPassword(text, NULL, name);
}

/** Import and name an DSA private key from an DSA private key in
 * encrypted PEM format PKCS #8.
 * 
 * @param text The PEM encoded PKCS #8 text that represents an DSA
 * public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the DSA private key.
 * 
 * @param name The name to be attached to the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::importKeyFromASCIIWithPassword(const char *text, const char *password, const char *name)
{
   setKeyName(name);
   int retval = importPrivateKeyWithOptionalPassword(text, password);
   return retval;
}

/** Export an DSA private key to some PEM format PKCS #8 text.
 * 
 * @param[out] text A pointer to a place to put a pointer to the
 * exported key in PEM encoded PKCS #8 text format. The responsibility
 * for freeing the new string is transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::exportKeyToASCII(char **text) const
{
   return getPEMKeyData(text);
}

/** Export an DSA private key to some PEM format PKCS #8 text
 * encrypted with the given password.
 * 
 * @param[out] text A pointer to a place to put a pointer to the
 * exported key in encrypted PEM encoded PKCS #8 text format. The
 * responsibility for freeing the new string is transferred to the
 * caller.
 * 
 * @param password The password to encrypt and decrypt the key with.
 * 
 * @return Returns zero on success, non-zero on failure. */
int DSAPrivateKey::exportKeyToASCIIWithPassword(char **text, const char *password) const
{
   return getPEMKeyData(text, password);
}
